package com.fyyg.common.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public final class HttpTookit {
	private static Log log = LogFactory.getLog(HttpTookit.class);

	public static String doGet(String url, String queryString) {
		String response = null;
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		try {
			if (StringUtils.isNotBlank(queryString))
				method.setQueryString(URIUtil.encodeQuery(queryString));
			client.executeMethod(method);
			if (method.getStatusCode() == 200)
				response = method.getResponseBodyAsString();
		} catch (URIException e) {
			log.error("执行HTTP Get请求时，编码查询字符串“" + queryString + "”发生异常！", e);
		} catch (IOException e) {
			log.error("执行HTTP Get请求" + url + "时，发生异常！", e);
		} finally {
			method.releaseConnection();
		}
		return response;
	}

	public static String doPost(String url, Map<String, String> params) {
		String response = null;
		HttpClient client = new HttpClient();
		HttpMethod method = new PostMethod(url);
		Iterator it = params.entrySet().iterator();
		while (it.hasNext())
			;
		if (params != null) {
			HttpMethodParams p = new HttpMethodParams();
			for (Iterator localIterator1 = params.entrySet().iterator(); localIterator1
					.hasNext();) {
				Entry entry = (Map.Entry) localIterator1.next();
				p.setParameter((String) entry.getKey(), entry.getValue());
			}
			method.setParams(p);
		}
		try {
			client.executeMethod(method);
			if (method.getStatusCode() == 200)
				response = method.getResponseBodyAsString();
		} catch (IOException e) {
			log.error("执行HTTP Post请求" + url + "时，发生异常！", e);
		} finally {
			method.releaseConnection();
		}

		return response;
	}

	public static String sendGet(String url) {
		String msg = "";
		try {
			HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(
					url).openConnection();
			msg = creatConnection(url, httpURLConnection);
		} catch (IOException io) {
			log.error("http close" + io);
		}
		System.out.println("信息发送情况1：" + msg);
		return msg;
	}

	private static String creatConnection(String url,
			HttpURLConnection httpURLConnection) {
		String msg = "";
		try {
			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
			httpURLConnection = (HttpURLConnection) new URL(url)
					.openConnection();
			httpURLConnection.setRequestMethod("GET");
			httpURLConnection.setRequestProperty("Content-Type",
					"text/html;charset=utf-8");
			msg = receiveMessage(httpURLConnection);
		} catch (IOException io) {
			io.printStackTrace();
			log.error("Http Connect to :" + url + " " + "IOFail!");
		} catch (Exception ex) {
			log.error("Http Connect to :" + url + " " + "Failed" + ex);
		} finally {
			closeConnection(httpURLConnection);
		}
		return msg;
	}

	private static void closeConnection(HttpURLConnection httpURLConnection) {
		try {
			if (httpURLConnection != null)
				httpURLConnection.disconnect();
		} catch (Exception localException) {
		}
	}

	private static String receiveMessage(HttpURLConnection httpURLConnection) {
		String responseBody = null;
		try {
			InputStream httpIn = httpURLConnection.getInputStream();
			if (httpIn != null) {
				ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
				byte tempByte;
				while (-1 != (tempByte = (byte) httpIn.read())) {
					byte tempByte1 = 0;
					byteOut.write(tempByte1);
				}
				responseBody = new String(byteOut.toByteArray(), "utf-8");
			}
		} catch (IOException ioe) {
			log.error("Http Connect tosss :" + ioe.getLocalizedMessage() + " "
					+ "IOEFail!");
			return null;
		}
		return responseBody;
	}

//	public static String getRealIpAddr(HttpServletRequest request) {
//		if (null == request) {
//			return "127.0.0.1";
//		}
//
//		String ip = request.getHeader("X-Real-IP");
//		if ((ip == null) || (ip.length() == 0)
//				|| ("unknown".equalsIgnoreCase(ip))) {
//			ip = request.getHeader("Proxy-Client-IP");
//		}
//		if ((ip == null) || (ip.length() == 0)
//				|| ("unknown".equalsIgnoreCase(ip))) {
//			ip = request.getHeader("WL-Proxy-Client-IP");
//		}
//		if ((ip == null) || (ip.length() == 0)
//				|| ("unknown".equalsIgnoreCase(ip))) {
//			ip = request.getRemoteAddr();
//		}
//		return ip;
//	}

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip;
    }
	
	public static String getRealIpAddr(HttpServletRequest request) {
		if (null == request) {
			return "127.0.0.1";
		}
		
        String ip = getIpAddress(request);
        ip = ip.contains(",") ? ip.split(",")[0] : ip;
        return ip;
	}
	
	public static String getPath(HttpServletRequest request) {
		String path = request.getContextPath();
		return request.getScheme() + "://" + request.getServerName() + ":"
				+ request.getServerPort() + path + "/";
	}
}
